<script lang="ts">
import { h, ref, type VNode } from 'vue'

export default {
  setup(_, { slots }) {
    const activeIdx = ref(0)

    return () => {
      const vNodes = slots.default?.() || []
      let idx = 0
      const tabPanes: VNode[] = []
      const tabHeadings: VNode[] = []

      for (const n of vNodes) {
        if (!(n.type as any).__TAB__) {
          continue
        }

        let props = n.props
        if (!props) {
          props = {}
          n.props = {}
        }
        if (props.title == null) {
          props.title == ''
        }
        const title = props.title
        props.__keyIdx = idx
        props.__activeIdx = activeIdx
        tabPanes.push(n)
        const keyIdx = idx

        const tabHeading = h(
          'li',
          {
            key: 'tab-heading-' + keyIdx,
            class: {
              'is-active': activeIdx.value === keyIdx
            },
            onClick() {
              activeIdx.value = keyIdx
            }
          },
          h('a', null, title)
        )
        tabHeadings.push(tabHeading)
        idx++
      }

      return [
        h('div', { class: 'tabs', style: { 'margin-bottom': 0 } }, [h('ul', null, tabHeadings)]),
        ...tabPanes
      ]
    }
  }
}
</script>
